$(function () {
    // 1.1 获取裁剪区域的 DOM 元素
    var img = $('#image')
    // 1.2 配置选项
    const options = {
        // 纵横比
        aspectRatio: 1,
        // 指定预览区域
        preview: '.img-preview'
    }
    // 1.3 创建裁剪区域
    img.cropper(options)

    $('#chooseImageBtn').on('click',function(){
        $('#chooseImageIpt').click()
    })

    $('#chooseImageIpt').on('change',function(){
        let file = this.files[0]
        if(file === undefined) {
            return layui.layer.msg('请选择上传图片！')
        }
        let url = URL.createObjectURL(file)
        $('#image').cropper('destroy')
                .attr('src',url)
                .cropper(options)
    })

    $('#uploadBtn').on('click',function(){
        let dataURL = img.cropper('getCroppedCanvas',{
            width: 100,
            height: 100
        }).toDataURL('image/png')

        axios({
            method: 'POST',
            url: '/my/update/avatar',
            data: 'avatar=' + encodeURIComponent(dataURL)
        }).then(({ data:res }) => {
            if(res.status !== 0) {
                return layui.layer.msg(res.message)
            }
            layui.layer.msg('更新头像成功！')
            window.parent.getUserInfo()
        })
    })
})